package com.hitcoder.common

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.hitcoder.network.interfaces.FileDownload
import com.hitcoder.network.model.Cover
import com.hitcoder.network.model.FileInfo
import com.hitcoder.network.utils.RequestBodyBuilder
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.io.File

class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //普通接口
        normal.setOnClickListener {
            normalInterface()
        }

        //文件上传接口
        upload.setOnClickListener {
            upload()
        }

        //文件下载接口
        download.setOnClickListener {
            downloadFile()
        }

        //取消下载文件
        cancel.setOnClickListener {
            net.canDownloadByTag("aaa")
        }

    }

    private fun normalInterface() {
        val loginRequest = LoginRequest("admin", "1234567", "android")

        //同步执行
        launch(Dispatchers.IO) {

            val loginData =
                net.getService(NetworkInterface::class.java)
                    .login(requestBody(loginRequest))
                    .exe()
            withContext(Dispatchers.Main) {
                textView.text = loginData.toString()
                Log.e("TAG", loginData.toString())
            }
        }

        //异步执行
        val enQ = net.getService(NetworkInterface::class.java)
            .login(requestBody(loginRequest))
            .enQ { code, message, data ->
                textView.text = "code: $code  message: $message  data: $data"
                Log.e("TAG", "code: $code  message: $message  data: $data")
            }
        //取消
        enQ.cancel()
        //aaa
    }

    private fun upload() {
        launch(Dispatchers.IO) {
            val file = File(getExternalFilesDir(null)?.absolutePath, "1.jpg")
            val file2 = File(getExternalFilesDir(null)?.absolutePath, "2.jpg")

            Log.e("TAG", "totalLength : ${file.length() + file2.length()}")

            val callback: (bytesWritten: Long, contentLength: Long, done: Boolean) -> Unit =
                { read, total, done ->
                    textView.text = Thread.currentThread().name + " 进度： " + read * 100 / total
                    Log.e(
                        "TAG",
                        Thread.currentThread().name + " 进度： " + read * 100 / total
                    )
                }
            
            val parts = RequestBodyBuilder()
                .addParam("a", "你好")
                .addFile(FileInfo("file", "1.jpg", file))
                .addFile(FileInfo("file2", "2.jpg", file2))
                .buildMultipartBody().parts

            val executeExa =
                net.getRequestProgressService(NetworkInterface::class.java, callback)
                    .upload(parts).exe()

            Log.e("TAG", executeExa.toString())
        }
    }

    private fun downloadFile() {
        net.downloadFile("http://app.2345.cn/appsoft/81595.apk",
            getExternalFilesDir(null)?.absolutePath + "/kuake.apk",
            object : FileDownload {
                override fun cover(): Cover {
                    return Cover.RENAME
                }

                override fun downloadStart() {
                    Log.e("TAG", "开始下载")
                    textView.text = "开始下载"
                }

                override fun downloadInProgress(writeBytes: Long, totalLength: Long) {
                    textView.text =
                        Thread.currentThread().name + " 进度： " + writeBytes * 100 / totalLength
                    Log.e(
                        "TAG",
                        Thread.currentThread().name + " 进度： " + writeBytes * 100 / totalLength
                    )
                }

                override fun downloadSuccess(filePath: String) {
                    Log.e("TAG", "下载完成：$filePath")
                    textView.text = "下载完成：$filePath"
                }

                override fun downloadFail(errorMessage: String) {
                    textView.text = "下载失败：$errorMessage"
                    Log.e("TAG", "下载失败：$errorMessage")
                }

                override fun downloadCancel() {
                    textView.text = "取消下载"
                }
            }).tag("aaa")
    }

}